package org.devops

def init(harborAddr, harborUid, appName, imageName, dockerTemplate) {
    this.harborAddr = harborAddr
    this.harborUid = harborUid
    this.appName = appName
    this.imageName = imageName
    this.dockerTemplate = dockerTemplate
    this.tools = new Tools()
    return this
}

def login() {
    withCredentials([usernamePassword(credentialsId: this.harborUid, usernameVariable: 'user', passwordVariable: 'pswd')]) {
        sh 'echo ${pswd} | docker login ' + "${this.harborAddr}" + ' -u ${user} --password-stdin'
    }
    return this
}

def build() {
    tools.printColor("构建docker镜像: ${imageName}", "green")

    items = this.dockerTemplate.split("/")
    templateName = items[items.size() - 1]
    dockerPath = this.dockerTemplate - ("/" + templateName)

    sh """
        rm -f ${dockerPath}/*.jar
        mv ${this.appName}/target/*.jar ${dockerPath}
       """

    jarName = findFiles(glob: "${dockerPath}/*.jar")[0].name

    sh """
        /bin/cp ${dockerTemplate} ${dockerPath}/Dockerfile
        sed -i 's#{{jarName}}#${jarName}#g' ${dockerPath}/Dockerfile
        docker build ${dockerPath} -t ${imageName}
       """

    return this
}

def push() {
    tools.printColor("上传docker镜像: ${imageName}", "green")

    sh """
         docker push ${imageName}
       """

    return this
}

def getDockerfileDir() {
    return this.dockerfile.split("/")[0] + '/' + dockerfile + this.dockerfile.split("/")[1]
}
